package weifei.live.simulation.im.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import weifei.live.simulation.entity.*;
import weifei.live.simulation.im.cmd.Message;
import weifei.live.simulation.im.entity.GroupAdminerMessageCache;
import weifei.live.simulation.im.entity.GroupUserMessageCache;
import weifei.live.simulation.im.entity.UserAdminerMessageCache;
import weifei.live.simulation.im.entity.UserFriendMessageCache;

import java.util.List;


@Service("ChatService")
public class ChatService
{
    private final User dao_user = new User();
    private final UserFriend dao_user_friend = new UserFriend();
    private final ChatGroup dao_group = new ChatGroup();
    private final GroupMember dao_group_member = new GroupMember();

    private final UserFriendMessageCache dao_friend_message_cache = new UserFriendMessageCache();
    private final GroupUserMessageCache dao_group_user_message_cache = new GroupUserMessageCache();
    private final UserAdminerMessageCache dao_user_adminer_message_cache = new UserAdminerMessageCache();
    private final GroupAdminerMessageCache dao_group_adminer_message_cache = new GroupAdminerMessageCache();



    /**
     * 有无 用户
     * */
    public boolean hasUser(int userId)
    {
        QueryWrapper<User> qw_user = new QueryWrapper<>();
        qw_user.eq(User.Column.ID.getName(), userId);
        return this.dao_user.selectOne(qw_user) != null;
    }


    /**
     * 有无 群聊
     * */
    public boolean hasGroup(int groupId)
    {
        QueryWrapper<ChatGroup> qw_group = new QueryWrapper<>();
        qw_group.eq(ChatGroup.Column.ID.getName(), groupId);
        return this.dao_group.selectOne(qw_group) != null;
    }


    /**
     * 用户 是否加入了 群聊
     * */
    public boolean hasJoinedGroup(int userId, int groupId)
    {
        QueryWrapper<GroupMember> qw_group_member = new QueryWrapper<>();
        qw_group_member.eq(GroupMember.Column.UserID.getName(), userId);
        qw_group_member.eq(GroupMember.Column.GroupID.getName(), groupId);
        return this.dao_group_member.selectOne(qw_group_member) != null;
    }


    public boolean bothFriend(int userId1, int userId2)
    {
        QueryWrapper<UserFriend> qw_friend = new QueryWrapper<>();
        qw_friend.eq(UserFriend.Column.UserID.getName(), userId1);
        qw_friend.eq(UserFriend.Column.FriendID.getName(), userId2);
        var relationship1 = this.dao_user_friend.selectOne(qw_friend);
        if (relationship1 == null)
            return false;

        qw_friend.clear();
        qw_friend.eq(UserFriend.Column.UserID.getName(), userId2);
        qw_friend.eq(UserFriend.Column.FriendID.getName(), userId1);
        var relationship2 = this.dao_user_friend.selectOne(qw_friend);
        if (relationship2 == null)
            return false;

        return true;
    }


    public void changeUserState(int userId, User.State state)
    {
        QueryWrapper<User> qw_user = new QueryWrapper<>();
        qw_user.eq(User.Column.ID.getName(), userId);
        var target = this.dao_user.selectOne(qw_user);
        if (target == null)
            return;
        target.setState(state);
        target.updateById();
    }




    /**
     * user 中的 stateID
     * 1 为 离线
     * 2 为 在线
     * */
    public Integer[] getOfflineUserIds()
    {
        QueryWrapper<User> qw_user = new QueryWrapper<>();
        qw_user.eq(User.Column.State.getName(), User.State.Offline);
        var list = this.dao_user.selectList(qw_user);
        var result = new Integer[list.size()];
        for(var i = 0; i < list.size(); i++)
        {
            result[i] = list.get(i).getId();
        }
        return result;
    }


    public Integer[] getGroupUserIds(int groupId)
    {
        QueryWrapper<GroupMember> qw_group_member = new QueryWrapper<>();
        qw_group_member.eq(ChatGroup.Column.ID.getName(), groupId);
        var list = this.dao_group_member.selectList(qw_group_member);
        var result = new Integer[list.size()];
        for(var i = 0; i < list.size(); i++)
        {
            result[i] = list.get(i).getUserId();
        }
        return result;
    }




    /**
     * 缓存发送给朋友的消息
     * */
    public void cacheUserFriendMessage(int friendId, Message message)
    {
        var cache = new UserFriendMessageCache(
                message.getType(),
                message.getFormat(),
                message.getSenderId(),
                friendId,
                message.getContent(),
                message.getSendTime()
        );
        if (cache.insert())
            System.out.println("发给用户" + friendId + "的消息 " + cache + " 已缓存");
    }


    public void cacheUserAdminerMessage(Integer userId, Message message)
    {
        var adminerId = message.getSenderId();
        var cache = new UserAdminerMessageCache(
            message.getType(),
            message.getFormat(),
            adminerId,
            userId,
            message.getContent(),
            message.getSendTime()
        );
        if (cache.insert())
        {
            if (adminerId == null)
                System.out.println("服务器 发给用户" + userId + "的消息 " + cache + " 已缓存");
            else
                System.out.println("管理员" + adminerId + "发给用户" + userId + "的消息 " + cache + " 已缓存");
        }
    }


    /**
     * 群聊消息都需要缓存，不用像friendMessage那样只是缓存个别
     * */
    public void cacheGroupUserMessage(Message message)
    {
        var destination = message.getDestination();
        var senderId = message.getSenderId();
        var targetIds = message.getTargetIds();
        if (destination != Message.Destination.UserToGroup)
        {
            System.err.println("不是UserToGroup消息，调（diao）错了");
            return;
        }
        if (senderId == null)
        {
            System.err.println("senderID 为 null 的 UserToGroup 消息，缓存失败");
            return;
        }
        if (targetIds == null)
        {
            System.err.println("targetIds 为 null 的 UserToGroup 消息，缓存失败");
            return;
        }

        for (var i : targetIds)
        {
            var cache = new GroupUserMessageCache(
                    i,
                    message.getType(),
                    message.getFormat(),
                    message.getSenderId(),
                    message.getContent(),
                    message.getSendTime()
                );
            if (cache.insert())
                System.out.println("用户" + senderId + " 发到群聊" + i + " 的消息 " + cache + " 已缓存");
        }

    }



    public void cacheGroupAdminerMessage(Message message)
    {
        var destination = message.getDestination();
        var adminerId = message.getSenderId();          // 为 null 则为 服务器发送的
        var targetIds = message.getTargetIds();         // 为 null 则为 广播消息
        if (destination != Message.Destination.Group)
        {
            System.err.println("不是Group消息，调（diao）错了");
            return;
        }


        // 服务器 广播给所有群聊的消息
        if (targetIds == null)
        {
            var cache = new GroupAdminerMessageCache(
                null,
                message.getType(),
                message.getFormat(),
                adminerId,
                message.getContent(),
                message.getSendTime()
            );
            if (cache.insert())
            {
                if (adminerId == null)
                    System.out.println("服务器 广播给所有群聊的消息 " + cache + " 已缓存");
                else
                    System.out.println("管理员" + adminerId + " 广播给所有群聊的消息 " + cache + " 已缓存");
            }
            return;
        }


        // 服务器 广播给部分群聊的消息
        // 管理员 广播给部分群聊的消息
        for (var i : targetIds)
        {
            var cache = new GroupAdminerMessageCache(
                i,
                message.getType(),
                message.getFormat(),
                adminerId,
                message.getContent(),
                message.getSendTime()
            );
            if (cache.insert())
            {
                if (adminerId == null)
                    System.out.println("服务器 广播给群聊" + i + "的消息 " + cache + " 已缓存");
                else
                    System.out.println("管理员" + adminerId + " 广播给群聊" + i + " 的消息 " + cache + " 已缓存");
            }
        }
    }


    public List<UserFriendMessageCache> getFriendMessageCacheListByUserID(int userId)
    {
        QueryWrapper<UserFriendMessageCache> qw_user_message_friend_cache = new QueryWrapper<>();
        qw_user_message_friend_cache.eq(UserFriendMessageCache.Column.ReceiverID.getName(), userId);
        return this.dao_friend_message_cache.selectList(qw_user_message_friend_cache);
    }


    public List<GroupUserMessageCache> getGroupMessageCacheListByGroupID(int groupId)
    {
        QueryWrapper<GroupUserMessageCache> qw_group_user_message_cache = new QueryWrapper<>();
        qw_group_user_message_cache.eq(GroupUserMessageCache.Column.GroupID.getName(), groupId);
        return this.dao_group_user_message_cache.selectList(qw_group_user_message_cache);
    }


    /**
     * 全体UserAdminerMessageCache
     * */
    public List<UserAdminerMessageCache> getAllUserAdminerMessageCacheList()
    {
        QueryWrapper<UserAdminerMessageCache> qw_user_message_adminer_cache = new QueryWrapper<>();
        qw_user_message_adminer_cache.eq(UserAdminerMessageCache.Column.ReceiverID.getName(), null);
        return this.dao_user_adminer_message_cache.selectList(qw_user_message_adminer_cache);
    }

    /**
     * 个别用户的UserAdminerMessageCache
     * */
    public List<UserAdminerMessageCache> getUserAdminerMessageCacheListByUserID(int userId)
    {
        QueryWrapper<UserAdminerMessageCache> qw_user_message_adminer_cache = new QueryWrapper<>();
        qw_user_message_adminer_cache.eq(UserAdminerMessageCache.Column.ReceiverID.getName(), userId);
        return this.dao_user_adminer_message_cache.selectList(qw_user_message_adminer_cache);
    }


    /**
     * 全体GroupAdminerMessageCache
     * */
    public List<GroupAdminerMessageCache> getAllGroupAdminerMessageCacheList()
    {
        QueryWrapper<GroupAdminerMessageCache> qw_group_message_adminer_cache = new QueryWrapper<>();
        qw_group_message_adminer_cache.eq(GroupAdminerMessageCache.Column.GroupID.getName(), null);
        return this.dao_group_adminer_message_cache.selectList(qw_group_message_adminer_cache);
    }

    /**
     * 个别群聊的GroupAdminerMessageCache
     * */
    public List<GroupAdminerMessageCache> getGroupAdminerMessageCacheListByGroupID(int groupId)
    {
        QueryWrapper<GroupAdminerMessageCache> qw_group_message_adminer_cache = new QueryWrapper<>();
        qw_group_message_adminer_cache.eq(GroupAdminerMessageCache.Column.GroupID.getName(), groupId);
        return this.dao_group_adminer_message_cache.selectList(qw_group_message_adminer_cache);
    }



}



